package com.btpj.jetpack.base

import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.paging.DataSource
import androidx.paging.LivePagedListBuilder
import androidx.paging.PagedList

/**
 * 列表类Activity对应的ViewModel基类
 *
 * @author LTP 2020/7/21
 */
abstract class BaseListViewModel<T> : ViewModel() {

    var pageData: LiveData<PagedList<T>>
    var mDataSource: DataSource<Int, T>? = null

    init {
        val config = PagedList.Config.Builder()
            .setPageSize(10)
            .setInitialLoadSizeHint(10)
            .build()

        val factory = object : DataSource.Factory<Int, T>() {
            override fun create(): DataSource<Int, T> {
                //使用 || 或者会导致刷新的时候 create会被不停的调用
                if (mDataSource == null || mDataSource?.isInvalid != false) {
                    mDataSource = createDataSource()
                }
                return mDataSource!!
            }
        }
        pageData = LivePagedListBuilder<Int, T>(factory, config).build()
    }

    abstract fun createDataSource(): DataSource<Int, T>
}